<template>
  <div class="menu-permission">
    <el-card>
      <el-tree
        ref="menuTree"
        :data="menuTreeData"
        show-checkbox
        node-key="menuId"
        :default-expand-all="true"
        :props="defaultProps"
        @check-change="handleCheckChange"
      >
      </el-tree>
      <div class="btn-group" style="margin-top: 20px;">
        <el-button type="primary" @click="handleSave">保存</el-button>
        <el-button @click="resetSelection">重置</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import { post } from '@/api/my_axios'

export default {
  name: 'MenuPermission',
  data () {
    return {
      // 菜单树数据
      menuTreeData: [],
      // 默认属性配置
      defaultProps: {
        children: 'children', // 子节点字段
        label: 'menuName', // 显示名称字段
        key: 'menuId' // 唯一标识字段
      },
      // 已勾选的菜单ID
      checkedMenuIds: []
    }
  },
  methods: {
    // 获取菜单数据并处理为树结构
    async fetchMenuData () {
      // try {
      //   const response = await this.$axios.get("/api/menu"); // 替换为实际接口地址
      //   const rawData = response.data.data || [];
      //   this.menuTreeData = this.formatToTree(rawData);
      // } catch (error) {
      //   console.error("获取菜单数据失败:", error);
      //   Message.error("获取菜单数据失败，请稍后重试");
      // }
      post('/api/crm/sys/manage/crm/function/list', {
        pageNum: 0,
        pageSize: 500
      }).then(req => {
        if (req && req.code === 200) {
          const rawData = req.data || []
          this.menuTreeData = this.formatToTree(rawData)
          // req.data.forEach(v => {
          //   this.menu_list.push({
          //     label: v.functionName + " (" + v.perms + ")",
          //     key: v.functionId,
          //     pinyin: v.functionName + v.perms
          //   });
          // });
        }
      })
    },

    // 格式化数据为树形结构
    formatToTree (data) {
      const map = {}
      const result = []
      data.forEach((item) => (map[item.menuId] = { ...item, children: [] }))
      data.forEach((item) => {
        if (item.parentId !== '-1') {
          map[item.parentId]?.children.push(map[item.menuId])
        } else {
          result.push(map[item.menuId])
        }
      })
      return result
    },

    // 勾选变化事件处理
    handleCheckChange (node, isChecked, childrenChecked) {
      this.checkedMenuIds = this.$refs.menuTree.getCheckedKeys()
    },

    // 保存操作
    async handleSave () {
      try {
        const payload = { menuIds: this.checkedMenuIds }
        await this.$axios.post('/api/menu/savePermissions', payload) // 替换为实际接口地址
        Message.success('权限保存成功！')
      } catch (error) {
        console.error('权限保存失败:', error)
        Message.error('权限保存失败，请稍后重试')
      }
    },

    // 重置勾选
    resetSelection () {
      this.$refs.menuTree.setCheckedKeys([])
      this.checkedMenuIds = []
    }
  },

  // 生命周期：挂载时获取菜单数据
  mounted () {
    this.fetchMenuData()
  }
}
</script>

<style scoped>
.menu-permission {
  padding: 20px;
}
</style>
